﻿using Md.Api.Entity.DapperModels.MdDB;
using Md.Api.Model.Manage.SysMenu.Request;
using Md.Dapper.Repositories.Md;

namespace Md.Api.Service.Manage.SysMenu;
/// <summary>
/// 获取系统菜单树列表服务
/// </summary>
public class GetSysMenuTreeListService : ApiBase<RequestGetSysMenuListModel>
{
    /// <summary>
    /// 系统菜单仓储
    /// </summary>
    public SysMenuRep sysMenuRep { get; set; }
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        var model = new SysMenuModel();

        model.MenuName = Parameter.MenuName;
        model.ParentId = Parameter.ParentId.HasValue ? Convert.ToInt64(Parameter.ParentId) : -1;
        model.IsFrame = Parameter.IsFrame.HasValue ? Convert.ToInt32(Parameter.IsFrame) : -1;
        model.IsCache = Parameter.IsCache.HasValue ? Convert.ToInt32(Parameter.IsCache) : -1;
        model.MenuType = Parameter.MenuType;
        model.Visible = Parameter.Visible;
        model.Status = Parameter.Status;
        model.CreateBy = Parameter.CreateBy;
        model.UpdateBy = Parameter.UpdateBy;

        var menus = sysMenuRep.GetSysMenuList(model, Parameter.OrderBy, Parameter.IsDesc).ToList();

        Result.Data = BuildMenuTree(menus, 0);
    }

    public List<SysMenuModel> BuildMenuTree(List<SysMenuModel> menus, long parentId)
    {
        var result = new List<SysMenuModel>();

        var list = menus.Where(s => s.ParentId == parentId).ToList();

        foreach (var menu in list)
        {
            result.Add(menu);

            var children = BuildMenuTree(menus, menu.MenuId);

            if (children.Count() > 0)
            {
                menu.Children = children;
            }
        }

        return result;
    }
}

